OP_NON = 0
OP_ASK = 1
OP_ALL = 2
OP_IGN = 3
OP_SKP = 4
OP_AGN = 5

OP_NO = 0
OP_YES = 1
OP_NEXT = 2

op_short_answer = ['q', '', 'a', 'i', 's', 'b']
op_long_answer = ['quit', '', 'all', 'ignore', 'skip', 'back']

GL_NAME = 0
GL_CONTINENT = 0
GL_COUNTRY = 1
GL_STATE = 2
GL_CITY = 3
GL_DISTRICT = 4
GL_OWNER = 5
GL_CUSTOM = 6

GL_FROM = 16
GL_TO = 17
GL_LAT = 18
GL_LGT = 19
GL_DELIM = 20
GL_POSTCODE = 21
GL_METROCODE = 22
GL_AREACODE = 23

gl_desc = (['continent', GL_CONTINENT], ['country', GL_COUNTRY], \
	['state', GL_STATE], ['city', GL_CITY], ['district', GL_DISTRICT], \
	['owner', GL_OWNER], ['custom', GL_CUSTOM], \
	['ip-from', GL_FROM], ['ip-to-mask', GL_TO], \
	['latitude', GL_LAT], ['longtitude', GL_LGT], \
	['postal-code', GL_POSTCODE], ['metro-code', GL_METROCODE], \
	['area-code', GL_AREACODE])

class loc:
	def __init__(self):
		self.info = []
		self.range = (0, 0)
		self.coord = (0, 0)
	def clear(self):
		del self.info[:]
		self.range = (0, 0)
		self.coord = (0, 0)
	def path(self, index):
		i = 0
		s = ''
		for name, desc, t_flag, t_op, t_geo in self.info:
			s += name+'.'
			if i == index:
				break
			i += 1
		return s

class geo_helper_cli:
	def __init__(self):
		self.answer = []
	
	def ask(tip, answer):
		op = OP_ASK
		stop = 0
		for i in answer:
			if op_short_answer[i] != '':
				tip += op_long_answer[i]+'('+op_short_answer[i]+'), '
		tip = tip.rstrip(', ')
		tip += ':'
		while not stop:
			stop = 1
			s = raw_input(tip)
			r = s.split(',')
			if len(r) > 1:
				self.geo[path] = r[1]
				name = r[1]
			try:
				op = op_short_answer.index(r[0])
				if op == OP_NON:
					sys.exit(0)
			except ValueError:
				stop = 0
		return op
	
	def find(self, type):
		for t, v in self.answer:
			if type == t:
				return True, v
		return False, None
	def replace(self, type, value):
		for i, [t, v] in enumerate(self.answer):
			if type == t:
				self.answer[i] = [type, value]
				return
		self.answer.append([type, value])
	def custom(self):
		m = 0
		for t, v in self.answer:
			if t >= GL_CUSTOM and t < GL_FROM:
				if t > m:
					m = t
		if m:
			if m < GL_FROM-1:
				return m+1
			else:
				return 0
		else:
			return GL_CUSTOM
	def ready(self):
		r = [GL_DELIM, GL_FROM, GL_TO, GL_NAME]
		for t, v in self.answer:
			if t == GL_DELIM:
				r.remove(GL_DELIM)
			elif t == GL_FROM:
				r.remove(GL_FROM)
			elif t == GL_TO:
				r.remove(GL_TO)
			elif t >= GL_NAME and t < GL_FROM:
				r.remove(GL_NAME)
		return not len(r)

	def checkline(self, line):
		op = OP_NEXT
		del self.answer[:]
		print 'record:'
		print '  '+line
		ret, sep = self.find(GL_DELIM)
		if ret:
			rec = line.split(sep)
		else:
			rec = []
		while len(rec) < 3:
			sep = raw_input('Please input delimiter:')
			rec = line.split(sep)
		self.replace(GL_DELIM, sep)
		for v, r in enumerate(rec):
			print 'Select type for ['+r+']:'
			j = 0
			for i, [d, t] in enumerate(gl_desc):
				ret, value = self.find(t)
				if ret:
					continue
				print '  '+str(i)+'. '+d
				j += 1
			if not j:
				return OP_YES
			
			stop = 0
			while not stop:
				s = raw_input( \
					'next record(n), quit(q), <cr> to continue:')
				try:
					n = int(s)
					if not n < len(gl_desc):
						continue
					name, t = gl_desc[n]
					if t == GL_CUSTOM:
						t = self.custom()
						if t == 0:
							print 'Too many custom fields!'
							continue
					ret, value = self.find(t)
					if not ret:
						self.answer.append([t, v])
						stop = 1
					else:
						print 'Same field exists!'
				except ValueError:
					if s == 'q':
						if self.ready():
							return OP_YES
						else:
							return OP_NO
					elif s == 'n':
						return OP_NEXT
					elif s == '':
						stop = 1
		if self.ready():
			return OP_YES
		else:
			return op
	
	def check(self, file):
		ret = False
		fp = open(file, 'r')
		if fp:
			try:
				print 'Please select type'
				for line in fp:
					op = self.checkline(line)
					if op == OP_YES:
						ret = True
						break
					elif op == OP_NO:
						ret = False
						break
			finally:
				fp.close()
		return ret
		
class geo_helper:
	def __init__(self):
		self.loc = loc()
		self.geo = dict()
		self.key = []
		self.cli = geo_helper_cli()

	def realname(self, index):
		path = self.loc.path(index)
		if path in self.geo:
			return self.geo[path]
		name, desc, t_flag, t_op, t_geo = self.loc.info[index]
		return name
	
	def wizard(self):
		return OP_ALL
	def ask(self, index):
		name, desc = self.loc.info[index]
		return OP_ALL, name
	
	def read(self, line):
		return False
	def write(self, index):
		pass

	def check(self, file):
		return False
	def learn(self, line):
		pass

